package org.mtmi.ui.controls.midi.popups;

import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.mtmi.midi.MidiManager;
import org.mtmi.ui.IMG;
import org.mtmi.ui.M;
import org.mtmi.ui.controls.IContentProvider;
import org.mtmi.ui.controls.ILabelProvider;
import org.mtmi.ui.controls.ListView;
import org.mtmi.ui.controls.listeners.ISelectionListener;
import org.mtmi.ui.controls.listeners.SelectionEvent;
import org.mtmi.ui.controls.popups.AbstractButtonPopup;
import org.mtmi.ui.drawables.IDrawable;
import org.mtmi.ui.layouts.LayoutData;
import org.mtmi.ui.scenes.Scene;

import rwmidi.MidiOutput;

/**
 * Popup to choose a MIDI output port.
 *
 */
public class ChooseMidiOutputPopup extends AbstractButtonPopup implements ISelectionListener
{
	
	private static class LabelProvider implements ILabelProvider
	{
		@Override
		public IDrawable getImage(Object element) {
			if( element instanceof MidiOutput ) {
				return IMG.GetD( IMG.I_MIDI_PORT );
			}
			return null;
		}

		@Override
		public String getText(Object element) {
			return ((MidiOutput)element).getName();
		}
	}
	
	private class ContentProvider implements IContentProvider
	{
		@Override
		public Object[] getElements(Object input) {
			return MidiManager.getInstance().getMidiOutputs();
		}
	}
	
	private ListView lv_items;
	private MidiOutput current_output;
	
	public ChooseMidiOutputPopup( Scene scene, int flags ) {
		this( scene, "Choose MIDI Output:", flags );
	}
	
	public ChooseMidiOutputPopup( Scene scene, String title, int flags ) {
		super( scene, title, flags );
	}
	
	public MidiOutput getMidiOutput() { return current_output; }
	
	public void setMidiOutput( MidiOutput o ) {
		current_output = o;
		lv_items.setSelection( o );
	}
	
	@Override
	public Rectangle createContents( Scene _scene ) {
		
		lv_items = new ListView( _scene, getFlags()&M.SCENE_EDITOR_CONTROL );
		lv_items.addSelectionListener( this );
		lv_items.setLabelProvider( new LabelProvider() );
		lv_items.setContentProvider( new ContentProvider() );
		lv_items.setInput( this );
		
		Point sz = lv_items.computeSize( new LayoutData(_scene) );
		Point s = _scene.getSize();
		int w = sz.x;
		int h = s.y/2;
		int x = (s.x-w)/2;
		int y = (s.y-h)/2;
		lv_items.setBounds( x, y, w, h );
		
		return new Rectangle( x, y, w, h );
	}
	
	@Override
	protected void terminate( int id ) {
		lv_items.dispose();
		super.terminate( id );
	}
	
	@Override
	public void selectionChanged( SelectionEvent e ) {
		current_output = (MidiOutput)e.selection;
	}

	@Override
	public void selectionConfirmed(SelectionEvent e) {
		current_output = (MidiOutput)e.selection;
		terminate( OK );
	}
	
}
